<div class="layui-form seller-form"  action="" >
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">预约手机：</label>
            <div class="layui-input-inline seller-inline-3">
                <input type="text" name="mobile"  placeholder="请输入预约手机" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">预约人：</label>
            <div class="layui-input-inline seller-inline-3">
                <input type="text" name="name"  placeholder="请输入预约预约人" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label">预约时间：</label>
            <div class="layui-input-inline seller-inline-3">
                <input type="text" name="booking_time" id="date"  placeholder="请输入预约预约人" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <button class="layui-btn layui-btn-sm"  lay-submit lay-filter="payments-search"><i class="iconfont icon-chaxun"></i>筛选</button>
            <button type="button" class="layui-btn layui-btn-sm add-booking"><i class="layui-icon">&#xe608;</i> 添加</button>
        </div>
    </div>
</div>
<div class="table-body">
        <div class="layui-tab layui-tab-brief">
    <ul class="layui-tab-title" id="tab">
        <li class="layui-this" data-types="today">今日预约</li>
        <li data-types="all">所有预约</li>
    </ul>
    </div>
    <table id="paymentsSellerTable" lay-filter="paymentsSellerTable"></table>
</div>
<script>
    layui.use(['table','form','layer', 'laydate'], function(){
        let lock = false;
        var table = layui.table,form = layui.form,layer = layui.layer, laydate = layui.laydate;
        var type='today'
        laydate.render({
            elem: '#date' //指定元素
        });
        //第一个实例
        table.render({
            elem: '#paymentsSellerTable', //指定原始表格元素选择器（推荐id选择器）
            height: 'full-260',
            cellMinWidth: '80',
            page:true,
            limit:70,
            id:'paymentsSellerTable',
            url: "{:url('booking/index')}",
            where: {type: type},
            cols: [[ //表头
                {type:'numbers'},
                {field: 'bn',title:'房间编号',align:'center',width:100},
                {field: 'name', title: '订房人',align:'center',width:100},
                {field: 'mobile', title: '订房电话',align:'center',width:120},
                {field: 'booking_time', title: '预约时间',align:'center',width:120},
                {field: 'come_time', title: '预计到店',align:'center',width:180},
                {field: 'price', title: '支付金额',align:'center',width:100},
                {field: 'to_shop', title: '当前状态',align:'center',width:120,templet: function(data){
                        if(data.to_shop == 0){
                            return '<span>未到店</span>';
                        }else if(data.to_shop == 1){
                            return '<span style="color:red;">已到店</span>';
                        }else{
                            return '<span style="color:green;">已结束</span>';
                        }

                }},
                {field: 'type', title: '预留类型',align:'center',width:100, templet: function(data){
                        if(data.type == 1){
                            return '客户预约';
                        }else if(data.type == 2){
                            return '挂单';
                        }else{
                            return '招待';
                        }
                    }
                },
                {field: 'memo', title: '备注',align:'center',width:100},
                {fixed: 'right', width:270,title:'操作', align:'center', toolbar: '#payments'}
            ]]
        });
        
        $(document).on('click','.add-booking',function(){
            JsGet("{:url('Booking/add')}", function(e){
                window.box = layer.open({
                    type: 1,
                    content: e,
                    area: ['450px', '500px'],
                    title:'添加预约'
                });
            })
        });


        form.on('submit(add-booking)', function(data){
            JsPost("{:url('Booking/doAdd')}", data.field, function(res){
                if(res.status){
                    layer.close(window.box);
                    layer.msg(res.msg,{time:1300},function(){
                        table.reload('paymentsSellerTable');
                    });
                }else{
                    layer.msg(res.msg);
                }
            })
        });

        form.on('submit(payments-search)', function(data){
            table.reload('paymentsSellerTable', {
                where: data.field
                ,page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        $('#tab li').click(function() {
            type = $(this).data('types');
            table.reload('paymentsSellerTable', {
                where: {type: type}
                ,page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        })



        //监听表单提交  (edit)
        form.on('submit(booking-edit)', function(data){
            $.ajax({
                url:"{:url('Booking/edit')}",
                type:'post',
                data: data.field,
                success:function(res){
                    if(res.status == true){
                        layer.close(window.box);
                        layer.msg(res.msg, {time:1300},function(){
                            table.reload('paymentsSellerTable');
                        });
                    }else{
                        layer.msg(res.msg);
                    }
                }
            },'json');
        });


        //监听 操作状态
        form.on('switch(status)', function(obj){
            JsPost("{:url('Payments/changeStatus')}",{id:this.value,status:obj.elem.checked},function(res){
                layer.msg(res.msg);
            });
        });


        //监听工具条
        table.on('tool(paymentsSellerTable)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            if(layEvent === 'edit') { //编辑
                JsGet("{:url('Booking/edit')}?id=" + data.id, function(e){
                    window.box = layer.open({
                        type:1,
                        content:e,
                        area:['450px','500px'],
                        title:'编辑品牌'
                    })
                })
            }else if(layEvent === 'to_shop') {
                $.ajax({
                    url:"{:url('Booking/to_shop')}",
                    type:'post',
                    data: {'id':data.id},
                    success:function(res){
                        if(res.status == true){
                            layer.msg(res.msg, {time:1300},function(){
                                table.reload('paymentsSellerTable');
                            });
                        }else{
                            layer.msg(res.msg);
                        }
                    }
                },'json');
            }else if(layEvent == 'clean'){
                layer.confirm('真的要结束吗',{icon: 3,title:'提示'}, function(index){
                    $.ajax({
                        url:"{:url('Booking/clean')}",
                        type:'post',
                        data: {'id':data.id},
                        success:function(res){
                            if(res.status == true){
                                layer.msg(res.msg, {time:1300},function(){
                                    table.reload('paymentsSellerTable');
                                });
                            }else{
                                layer.msg(res.msg);
                            }
                        }
                    },'json');
                })
            }else if(layEvent == 'cancel'){
                $.ajax({
                    type: 'GET',
                    url: "{:url('Api/getToken')}",
                    dataType: 'json',
                    success: function (respon) {
                        book_cancel(data, respon.token);
                    },
                    error: function(error) {
                        if(error.responseJSON) {
                            layer.msg(error.responseJSON.msg);
                        } else {
                            layer.msg(error.statusText);
                        }
                    }
                })
                /*layer.confirm('真的要取消吗',{icon: 3,title:'提示'}, function(){
                    if(!lock) {
                        lock = true;
                        var index = layer.load(2);
                        $.ajax({
                            url: "{:url('Booking/cancel')}",
                            type: 'post',
                            data: {'id': data.id},
                            success: function (res) {
                                layer.close(index);
                                if (res.status == true) {
                                    layer.msg(res.msg, {time: 1300}, function () {
                                        table.reload('paymentsSellerTable');
                                    });
                                } else {
                                    layer.msg(res.msg);
                                }
                                setTimeout(function () {
                                    lock = false;
                                }, 1000);
                            }
                        }, 'json');
                    }else{
                        layer.msg("操作过于频繁");
                    }
                })*/
            }else if(layEvent === 'print_booking'){

                $.ajax({
                    url:"{:url('Booking/getBooking')}",
                    type:'post',
                    data: {'id':data.id},
                    success:function(res){
                        if(res.status == true){
                            let date = new Date();
                            let year = date.getFullYear();
                            let month = date.getMonth() + 1;
                            let day = date.getDate();
                            let hour = date.getHours();
                            let minute = date.getMinutes();

                            let booking = res.data;
                            console.log(booking);

                            if(booking.taocan && booking.taocan != ""){
                                booking.taocan = JSON.parse(booking.taocan);
                            }

                            LODOP = getLodop(document.getElementById('LODOP1'), document.getElementById('LODOP_EM1'));
                            LODOP.PRINT_INITA(0, 0, 230, 230, "打印条码");
                            LODOP.SET_PRINTER_INDEX(-1);
                            LODOP.SET_PRINT_PAGESIZE(1,580,-1,"");
                            LODOP.SET_PRINT_STYLE("FontSize", 12);
                            LODOP.SET_PRINT_STYLE("Bold", 1);
                            LODOP.ADD_PRINT_TEXT("30","30","230","20","房间套餐销售单");
                            LODOP.SET_PRINT_STYLE("FontSize", 12);
                            LODOP.SET_PRINT_STYLE("Bold", 1);
                            LODOP.ADD_PRINT_TEXT(70, 10, 230, 20, "房间编号：" + booking.bn);
                            LODOP.SET_PRINT_STYLE("FontSize", 10);
                            LODOP.SET_PRINT_STYLE("Bold", 1);
                            /*if(booking.taocan && typeof (booking.taocan) == 'object'){
                                LODOP.ADD_PRINT_TEXT(90, 10, 230, 20, "套餐：" + booking.taocan['name'] + "  -  ￥" + toDecimal2NoZero(Number(booking.price )));
                            }else{
                                LODOP.ADD_PRINT_TEXT(90, 10, 230, 20, "套餐：-");
                            }*/
                            LODOP.ADD_PRINT_TEXT(90, 10, 230, 20, "下单人：" + booking.nickname);
                            let x = 120
                            LODOP.SET_PRINT_STYLE("FontSize", 10);
                            LODOP.SET_PRINT_STYLE("Bold", 0);
                            if(booking.taocan && typeof (booking.taocan) == 'object'){
                                let goods = booking.taocan['goods']
                                for(let i = 0; i < goods.length; i++){
                                    let nk = "";
                                    if(strlen(goods[i].name) <= 24){
                                        let y = 24 - strlen(goods[i].name);
                                        for(let a = 0; a < y; a++){
                                            nk += " ";
                                        }
                                    }else{
                                        goods[i].name = goods[i].name.substring(0,21) + "..";
                                        nk += "  ";
                                    }
                                    LODOP.ADD_PRINT_TEXT(x, 10, 230, 20,  goods[i].name + nk + "x" + goods[i].total);
                                    x += 20
                                }
                            }else{
                                LODOP.SET_PRINT_STYLE("FontSize", 12);
                                LODOP.SET_PRINT_STYLE("Bold", 1);
                                LODOP.ADD_PRINT_TEXT(x,"10","230","20","房间套餐无其他内容");
                                x += 20
                            }


                            LODOP.SET_PRINT_STYLE("FontSize", 9);
                            LODOP.SET_PRINT_STYLE("Bold", 1);
                            LODOP.ADD_PRINT_TEXT(x + 10, 10, 230, 20, "总金额：￥" + toDecimal2NoZero(Number(booking.price )));

                            LODOP.SET_PRINT_STYLE("FontSize", 8);
                            LODOP.SET_PRINT_STYLE("Bold", 0);
                            LODOP.ADD_PRINT_TEXT(x + 30, 10, 230, 20, "打印时间：" + year + "/" + month + "/"+ day + " " + hour + ":"+ minute);
                            LODOP.SET_PRINT_STYLE("FontSize", 10);
                            LODOP.SET_PRINT_STYLE("Bold", 1);
                            if(booking.payment_code == "wechatpay"){
                                LODOP.ADD_PRINT_TEXT(x + 60, 10, 230, 20, "支付方式：微信支付");
                            }else if(booking.payment_code == "alipay"){
                                LODOP.ADD_PRINT_TEXT(x + 60, 10, 230, 20, "支付方式：支付宝支付");
                            }else if(booking.payment_code == "balance"){
                                LODOP.ADD_PRINT_TEXT(x + 60, 10, 230, 20, "支付方式：会员卡余额支付");
                            }
                            LODOP.SET_PRINT_STYLE("FontSize", 8);
                            LODOP.SET_PRINT_STYLE("Bold", 0);
                            LODOP.ADD_PRINT_TEXT(x + 90, 10, 230, 20, "-----------------------------------------");
                            LODOP.PREVIEW();
                        }else{
                            layer.msg(res.msg);
                        }
                    }
                },'json');
            } else if(layEvent === 'kd') {
                $.ajax({
                    type: 'GET',
                    url: "{:url('Api/getToken')}",
                    dataType: 'json',
                    success: function (respon) {
                        book_cancel(data, respon.token, true);
                    },
                    error: function(error) {
                        if(error.responseJSON) {
                            layer.msg(error.responseJSON.msg);
                        } else {
                            layer.msg(error.statusText);
                        }
                    }
                })
            }
            });
            var book_cancel = function(data, token, kd=false) {
                layer.confirm('真的要取消吗',{icon: 3,title:'提示'}, function(){
                    if(kd) {
                        var datas = {id: data.id, token: token, isrefund: 0}
                    } else {
                        var datas = {id: data.id, token: token, isrefund: 1};
                    }
                    var index = layer.load(2);
                    $.ajax({
                        url: "{:url('Booking/cancel')}",
                        type: 'post',
                        data: datas,
                        dataType: 'json',
                        success: function (res) {
                            layer.close(index);
                            if (res.status == true) {
                                layer.msg(res.msg, {time: 1300}, function () {
                                    table.reload('paymentsSellerTable');
                                });
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function (err) {
                            if(error.responseJSON) {
                                layer.msg(error.responseJSON.msg);
                            } else {
                                layer.msg(error.statusText);
                            }
                        }
                    });
                })
            }


    });
    function toDecimal2NoZero(x) {
        let f = Math.round(x * 100) / 100;
        let s = f.toString();
        return s;
    }

    function strlen(str){
        let len = 0;
        for (let i=0; i<str.length; i++) {
            let c = str.charCodeAt(i);
            //单字节加1
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
                len++;
            }
            else {
                len+=2;
            }
        }
        return len;
    }
</script>

<script type="text/html" id="status">
    <input type="checkbox" name="status" value="{{d.id}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="status" {{ d.status == 1 ? 'checked' : '' }}>
</script>

<script type="text/html" id="payments">
    <a class="layui-btn layui-btn-xs" lay-event="to_shop" {{ d.to_shop == 0 ? '' : 'style="display:none;"' }}>到店</a>
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <!--<a class="layui-btn layui-btn-xs" lay-event="print_booking">打印</a>-->
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="clean" {{d.to_shop == 1 ? '' : 'style="display:none;"' }}>结束</a>
    {{# if (d.pay_status != '2') { }}
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="kd">扣订</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="cancel">取消</a>
    {{# } }}
</script>